package com.yuanli.card.manage.config;


import com.yuanli.card.exception.ApplicationException;
import com.yuanli.card.exception.ServiceException;
import com.yuanli.card.res.ResponseBean;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author layne
 * @date 17-7-25
 */
@ControllerAdvice
public class AutoExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(AutoExceptionHandler.class);


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseBean exceptionHandler(HttpServletRequest request,Exception exception) {// 捕获运行时异常
        String msg = StringUtils.isBlank(exception.getMessage()) ? "系统异常" : exception.getMessage();
        logger.error("msg="+msg+";url="+request.getRequestURL(), exception);
        return ResponseBean.response().setCode(-1).setMessage(msg);
    }

    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public ResponseBean serviceExceptionHandler(HttpServletRequest request, ServiceException exception) {// 捕获自定义异常
        logger.error("code={},msg={},url={}", exception.getCode(), exception.getMessage(), request.getRequestURL());
        return ResponseBean.response().setCode(exception.getCode() == null ? -1 : exception.getCode()).setMessage(exception.getMessage());
    }

    @ExceptionHandler(ApplicationException.class)
    @ResponseBody
    public ResponseBean applicationExceptionHandler(HttpServletRequest request, ApplicationException exception) {// 捕获自定义异常
        String msg = StringUtils.isBlank(exception.getMessage()) ? "系统异常" : exception.getMessage();
        logger.error("msg="+msg+";url="+request.getRequestURL(), exception);
        return ResponseBean.response().setCode(-1).setMessage(msg);
    }
}
